package br.unicamp.ic.sgct.client.apresentacao.views;

import br.unicamp.ic.sgct.client.apresentacao.widgets.LabelCampoForm;
import br.unicamp.ic.sgct.client.dominio.to.AreaTO;
import br.unicamp.ic.sgct.client.dominio.to.AutorTO;
import br.unicamp.ic.sgct.client.dominio.to.ParticipanteTO;
import br.unicamp.ic.sgct.client.dominio.to.TrabalhoTO;
import br.unicamp.ic.sgct.server.dominio.servlets.FileUploadServlet;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import java.util.ArrayList;
import java.util.List;

//Exercicio 2 - 7
import org.gwtiger.client.widget.field.ListBoxFieldWidget;
//
import org.gwtiger.client.widget.field.TextAreaFieldWidget;
import org.gwtiger.client.widget.field.TextFieldWidget;


public class ViewInscricaoTrabalho extends Composite {

    private HTML strTabTitle = null;
    private int index = 0;
    //Exercicio 2 - 7
    private ListBoxFieldWidget txtbTipo = null;
    //
    private TextFieldWidget txtbTitulo = null;
    private TextAreaFieldWidget txtbResumo = null;
    private TextAreaFieldWidget txtbAutores = null;
    private ListBox lbArea = null;
    private ListBox lbParticipante = null;
    private VerticalPanel panelInscricaoTrabalho = new VerticalPanel();
    private Grid gridInscricaoTrabalho1 = new Grid(3, 1);
    private Grid gridInscricaoTrabalho2 = new Grid(3, 1);
    private HorizontalPanel panelHoriz = new HorizontalPanel();
    private HorizontalPanel panelADDH = new HorizontalPanel();
    private FileUploadForm fileUploadForm = new FileUploadForm();
    private static final String MSG_REQUIRED_ERR = "Campo(s) obrigatorio(s) n\u00e3o preenchido(s)!";
    private static final String MSG_RESUMO_GRANDE = "Tamanho máximo campo Resumo é 250 caracteres !";
    private static final String MSG_TITULO_GRANDE = "Tamanho máximo campo Titulo é 100 caracteres !";
    private static final String MSG_TIPO_GRANDE = "Tamanho máximo campo Tipo é 10 caracteres !";

    public String validaDadosFormulario() {
        String ret = null;
        if (!(txtbTitulo.validate()
                && txtbTipo.validate()
                && txtbResumo.validate()
                && lbArea.getSelectedIndex() != -1)) {
            ret = MSG_REQUIRED_ERR;
        } else if (txtbTitulo.getText().length() > 100) {
            ret = MSG_TITULO_GRANDE;
        } else if (txtbResumo.getText().length() > 250) {
            ret = MSG_RESUMO_GRANDE;
        }
        return ret;
    }

    public String validaArquivo() {
        String ret = null;
        if (fileUploadForm.getFilename() == null || fileUploadForm.getFilename().equals("")) {
            ret = MSG_REQUIRED_ERR;
        }
        return ret;
    }

    public TrabalhoTO obterTrabalhoTO() {
        TrabalhoTO to = new TrabalhoTO();
        to.setResumo(txtbResumo.getText());
        to.setTitulo(txtbTitulo.getText());
        to.setAutores(participantesSelected());
        to.setAreas(areasSelected());
        to.setNomeArquivo(fileUploadForm.getFilename());
        //Exercicio 2 - 7
        to.setTipo(txtbTipo.getSelectedValue());
        //
        return to;
    }

    private List<AutorTO> participantesSelected() {
        List<AutorTO> participantes = new ArrayList<AutorTO>();
        for (int i = 0; i < lbParticipante.getItemCount(); i++) {
            if (lbParticipante.isItemSelected(i)) {
                String ind = lbParticipante.getValue(i);
                long id = Long.parseLong(ind);
                ParticipanteTO participanteTO = new ParticipanteTO();
                participanteTO.setId(id);
                participantes.add(participanteTO);
            }
        }
        return participantes;
    }

    private List<AreaTO> areasSelected() {
        List<AreaTO> areas = new ArrayList<AreaTO>();
        for (int i = 0; i < lbArea.getItemCount(); i++) {
            if (lbArea.isItemSelected(i)) {
                String ind = lbArea.getValue(i);
                long id = Long.parseLong(ind);
                AreaTO areaTO = new AreaTO();
                areaTO.setId(id);
                areas.add(areaTO);
            }
        }
        return areas;
    }

    public ViewInscricaoTrabalho addH(Widget w) {
        panelADDH.add(w);
        return this;
    }

    public void clear() {
        txtbTipo.clear();
        txtbResumo.clear();
        txtbTitulo.clear();
        txtbAutores.clear();
        fileUploadForm.clear();

    }

    public ViewInscricaoTrabalho(String title, int index) {

        this.strTabTitle = new HTML(title);
        this.index = index;
        initPanel();

        initWidget(panelInscricaoTrabalho);
    }

    private void initPanel() {
        initGridSubmissaoTrabalho();
        panelInscricaoTrabalho.setVisible(false);
        panelInscricaoTrabalho.add(panelHoriz);
        this.panelHoriz.add(this.gridInscricaoTrabalho1);
        this.panelHoriz.add(this.gridInscricaoTrabalho2);
        panelInscricaoTrabalho.add(panelADDH);
    }

    public void montar(List<AreaTO> areas, List<ParticipanteTO> listParticipante) {
        this.gridInscricaoTrabalho1.setVisible(true);
        this.gridInscricaoTrabalho2.setVisible(true);
        montaLbArea(areas);
        montaLbParticipante(listParticipante);
    }

    private void montaLbParticipante(List<ParticipanteTO> participantes) {
        lbParticipante.clear();
        if (participantes != null) {
            if (participantes.size() > 5) {
                lbParticipante.setVisibleItemCount(5);
            } else {
                lbParticipante.setVisibleItemCount(participantes.size());
            }
            for (int i = 0; i < participantes.size(); i++) {
                lbParticipante.addItem(participantes.get(i).getPessoa().getNome(), String.valueOf(participantes.get(i).getId()));
            }
        }
    }

    private void montaLbArea(List<AreaTO> areas) {
        lbArea.clear();
        if (areas != null) {
            if (areas.size() > 5) {
                lbArea.setVisibleItemCount(5);
            } else {
                lbArea.setVisibleItemCount(areas.size());
            }
            for (int i = 0; i < areas.size(); i++) {
                lbArea.addItem(areas.get(i).getNome(), String.valueOf(areas.get(i).getId()));
            }
        }

    }

    private void initGridSubmissaoTrabalho() {
        HorizontalPanel panell = new HorizontalPanel();
        
        //Exercicio 2 - 7
        this.txtbTipo = new ListBoxFieldWidget("Tipo");
        txtbTipo.addItem("artigo");
        txtbTipo.addItem("resumo");
        //
        
        this.txtbTipo.setRequired(true);
        this.txtbResumo = new TextAreaFieldWidget("Resumo", 3, 5);
        this.txtbResumo.setRequired(true);
        //this.txtbArea = new TextFieldWidget("Area");
        //this.txtbArea.setRequired(true);
        this.txtbTitulo = new TextFieldWidget("Titulo");
        this.txtbTitulo.setRequired(true);
        this.txtbAutores = new TextAreaFieldWidget("Autores", 3, 5);
        this.txtbAutores.setRequired(true);
        //
        HorizontalPanel panellbArea = new HorizontalPanel();
        LabelCampoForm labelArea = new LabelCampoForm(" Areas: ");
        this.lbArea = new ListBox(true);
        panellbArea.add(labelArea);
        panellbArea.add(lbArea);
        //
        HorizontalPanel panellbParticipante = new HorizontalPanel();
        LabelCampoForm labelParticipante = new LabelCampoForm(" Participantes: ");
        this.lbParticipante = new ListBox(true);
        panellbParticipante.add(labelParticipante);
        panellbParticipante.add(lbParticipante);

        //
        gridInscricaoTrabalho1.setBorderWidth(0);
        gridInscricaoTrabalho1.setCellSpacing(1);
        gridInscricaoTrabalho1.setCellPadding(1);
        gridInscricaoTrabalho1.setTitle("Submissao confer\u00eancia selecionada...");
        gridInscricaoTrabalho1.setWidget(0, 0, this.txtbTitulo);
        gridInscricaoTrabalho1.setWidget(1, 0, this.txtbResumo);
        gridInscricaoTrabalho1.setWidget(2, 0, this.txtbTipo);
        gridInscricaoTrabalho2.setWidget(0, 0, panellbParticipante);
        gridInscricaoTrabalho2.setWidget(1, 0, panellbArea);
        gridInscricaoTrabalho2.setWidget(2, 0, this.fileUploadForm);

    }

    public void submit(TrabalhoTO trabalhoTO) {
        fileUploadForm.submit(trabalhoTO);

    }

    /**
     * @return the strTabTitle
     */
    public HTML getStrTabTitle() {
        return strTabTitle;
    }

    public class FileUploadForm extends Composite {

        private FormPanel form = null;
        private FileUpload upload = new FileUpload();
        private TrabalhoTO to = null;
        //private FileUploadServlet uploadServelet = new FileUploadServlet();
        

        private FileUploadForm() {
            form = new FormPanel();
            form.setAction("sisgesconftec/fileupload");
            form.setEncoding(FormPanel.ENCODING_MULTIPART);
            form.setMethod(FormPanel.METHOD_POST);
            VerticalPanel panel = new VerticalPanel();
            form.setWidget(panel);
            panel.add(upload);
            form.addSubmitHandler(new FormPanel.SubmitHandler() {

                @Override
                public void onSubmit(SubmitEvent event) {
                	//uploadServelet.doFilePost(, context)
                	
                    // This event is fired just before the form is submitted. We can take
                    // this opportunity to perform validation.
                }
            });
            form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

                @Override
                public void onSubmitComplete(final SubmitCompleteEvent event) {
                    
                	
                	//uploadServelet.doFilePost(event., context)
                	
                	//handler.handle(to);
                    /*
                    try {
                    controladoraLogin.obterParticipanteConferencia(conferenciaTO, new LoginListener.HandlerObterParticipanteConferencia() {

                    @Override
                    public void handleSucesso(ParticipanteTO result, ConferenciaTO to) {
                    handler.sucesso();
                    Window.alert(event.getResults());
                    }

                    @Override
                    public void handleErro(Throwable caught) {
                    Window.alert(caught.getMessage());
                    }
                    });
                    } catch (Exception e) {
                    controladoraLogin.setMensagemErro(e.getMessage());
                    }
                     *
                     */
                }
            });
            initWidget(form);
        }

        private String getFilename() {
            return this.upload.getFilename();
        }

        private void submit(TrabalhoTO trabalhoTO) {
            this.to = trabalhoTO;
            upload.setName("uploadArquivoIdTrabalho=" + trabalhoTO.getIdTrabalho());
            this.form.submit();
        }

        private void clear() {
            //upload.clear();
        }
    }
}
